﻿/*
创建人：zhangrj
日期：2024-07-23
描述：热表有限排产js
*/
var page = {
    pageTotal: 0,
    pageSize: 20,
    pageNumber: 1,
    rootPath: getRootPath(), //网站根路径
    url: getRootPath() + "/Ashx/ApsHandler/RbApsLimitedCapacityHandler.ashx", //热表排产一般处理程序
    apsUrl: getRootPath() + "/Ashx/ApsHandler/ApsLimitedCapacityHandler.ashx", //通用排产一般处理程序
    //初始化页面
    init: function () {
        page.bind();
        page.initPageData();
        NewcustomizedEasyuiPagination('pp'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        //列表加载
        $("#gdApsContainer").datagrid({
            toolbar: '#gdBtn',
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pageTotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                NewcustomizedEasyuiPagination('pp'); //定制化分页
                //提示消息样式
                $("#dvApsPool .tip").addClass('icon-standard-exclamation');
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'FAFACTORYNAME', title: '主制分厂', width: 100 },
                 { field: 'FACONTAINERNAME', title: '主制批次', width: 150 },
                 { field: 'CONTAINERNAME', title: '批次', width: 200, formatter: function (value, row, index) {
                     return '<a href="#" onclick = "page.viewGantt(\'' + row.CONTAINERID + '\')">' + value + '</a>';
                 }, styler: function (value, row, index) {
                     if (row.ENDTIME != null && dayjs(dayjs(row.ENDTIME).format('YYYY-MM-DD')) > dayjs(dayjs(row.PLANNEDCOMPLETIONDATE).format('YYYY-MM-DD'))) {
                         return 'background-color:#ffee00;';
                     }
                 }
                 },
                 { field: 'WORKFLOWINFO', title: '工艺信息', width: 150, formatter: function (value, row, index) {
                     return '<a href="#" onclick = "page.linkStepInfoParam(\'' + row.PRODUCTID + '\',\'' + row.PRODUCTNAME + '\',\'' + row.WORKFLOWID + '\',\'' + row.WORKFLOWNAME + '\')">' + value + '</a>';
                     //                     var url = "forms/Custom/ReBiao/RBStepParameterMaintPage.html?" +
                     //                     "pname=" + row.PRODUCTNAME + "&pid=" + row.PRODUCTID + "&wname=" + row.WORKFLOWNAME + "&wid=" + row.WORKFLOWID; //encodeURI(
                     //                     return '<a target="_blank" onclick="top.mainWorkPage.addTab(\'APS-工步生产周期维护\',\'' + url + '\',true);return false;" href="#" style=""  >' + value + '</a>';
                 }
                 },
                 { field: 'WORKFLOWSTEPNAME', title: '工序', width: 100 },
                 { field: 'SHIPPLANSTARTTIME', title: '转工计划开始', width: 120,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'SHIPPLANENDTIME', title: '转工计划结束', width: 120,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'STARTTIME', title: '滚动计划开始', width: 120,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'ENDTIME', title: '滚排计划结束', width: 120,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'NEXTCONTAINERNAME', title: '连续转工批次', width: 120 },
                 { field: 'EXPECTMATERIALDATE', title: '手动指定开始', width: 105, editor: { type: 'datebox' }, formatter: function (value, row, index) {
                     if (value === null || value === "") {
                         var shipPlanDate = dayjs(row.SHIPPLANSTARTTIME).format("YYYY-MM-DD");
                         if (dayjs(row.SHIPPLANSTARTTIME).format("YYYY-MM-DD HH:mm:ss") < dayjs(shipPlanDate + " 08:00:00").format("YYYY-MM-DD HH:mm:ss")) {
                             return dayjs(shipPlanDate + " 09:00:00").format("YYYY-MM-DD HH:mm:ss");
                         }
                         else {
                             return dayjs(shipPlanDate + " 09:00:00").add(1, 'day').format("YYYY-MM-DD HH:mm:ss");
                         }
                     }
                     else {
                         return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
                     }
                 }
                 },
                 { field: 'PLANOVERDUE', title: '计划超期', width: 80 },
                 { field: 'APSSEQUENCE', title: '顺序号', width: 60 },
                 { field: 'AMOUNT', title: '期量', width: 60 },
                 { field: 'LOGMESSAGE', title: '排产日志', width: 80, formatter: function (value, row, index) {
                     if (value != null) {
                         return '<div class="tip" title=' + value.replace(/[ ]|[\r\n]/g, "") + ' style="height:20px;color:red;cursor: pointer;" >' + '' + '</div>';
                     }
                 }
                 }
                ]]
        });
        //查询按钮
        $('#btnSearch').on("click", function () {
            page.pageNumber = 1;
            page.searchData();
        });
        //计算顺序号按钮
        $('#btnCalOrderNum').on("click", function () {
            page.calcOrderNum();
        });
        //排产计算按钮
        $('#btnApsCalculate').on("click", function () {
            page.calcApsPlan();
        });
        //添加到排产池
        $('#btnAddToPool').on("click", function () {
            page.addApsPool();
        });
        //移除排产池
        $('#btnRemovePool').on("click", function () {
            page.removeApsPool();
        });
        //排产异常导出
        $('#btnApsErrorExport').on("click", function () {
            page.exportApsLog();
        });
        //批量维护指定时间
        $('#btnEditManualStartDate').on("click", function () {
            page.openHandTimeForm();
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                //NewcustomizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            //            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            var pageNumber = Number($(this).parents('tr').find('.pagination-num').val());
            page.pageSize = $('#pp').find('.pageSize').val() == "" ? 10 : Number($('#pp').find('.pageSize').val());
            page.pageNumber = pageNumber;
            page.searchData();
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true);
            page.pageNumber = 1; page.pageTotal = 0
            $('#pp').pagination('refresh', {
                total: page.pageTotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });
        //手动指定日期保存
        $('#btnSaveManual').on("click", function () {
            handTimePage.saveManualDate();
        });
        //关闭手动指定弹窗
        $('#btnCloseManual').on("click", function () {
            $("#dgManual").dialog("close");
        });
    },
    //初始化页面数据
    initPageData: function () {
        page.post(page.url, { action: "InitRbApsLimitPageData" }, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            //主制分厂
            $('#txtMainFactoryID').combobox({
                valueField: 'FACTORYID',
                textField: 'FACTORYNAME',
                data: res.DBDataSet.dtFactory
            });
            //排产池
            $('#txtPoolID').combobox({
                valueField: 'APSPOOLID',
                textField: 'APSPOOLNAME',
                data: res.DBDataSet.dtPool
            });
            if (res.DBDataSet.dtPool.length > 0) {
                $('#txtPoolID').combobox('setValue', res.DBDataSet.dtPool[0].APSPOOLID); //默认第一个
            }
        });
    },
    //查询
    searchData: function () {
        var params = {
            pageSize: page.pageSize,
            pageIndex: page.pageNumber
        };
        var queryFormData = $("#queryForm").serializeArray();
        $.each(queryFormData, function () {
            params[this.name] = this.value;
        });
        if (params["PoolID"] === "" || params["PoolID"] === null) {
            displayMessage("请选择排产池", false);
            return;
        }
        page.post(page.url, { action: "GetApsPlanContainerData", params: JSON.stringify(params) }, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            page.pageTotal = res.RowCount;
            $("#gdApsContainer").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
        });
    },
    //计算顺序号
    calcOrderNum: function () {
        var poolID = $("#txtPoolID").combobox("getValue"); //获取排产池
        if (poolID === "" || poolID === null) {
            displayMessage("请选择排产池", false);
            return;
        }
        page.disableBtn();
        page.post(page.url, { action: "CalcContainerApsPriority", poolID: poolID }, true, function (res) {
            if (res.Result) {
                page.searchData();
            }
            displayMessage(res.Message, res.Result);
            page.enableBtn();
        });
    },
    //排产计算
    calcApsPlan: function () {
        var selectData = $('#gdApsContainer').datagrid('getChecked');
        if (selectData.length === 0) {
            displayMessage("请选择数据", false);
            return;
        }
        page.disableBtn();
        page.post(page.url, { action: "CalcContainerApsPlan", params: JSON.stringify(selectData) }, true, function (res) {
            page.searchData();
            displayMessage(res.Message, res.Result);
            page.enableBtn();
        });
    },
    //添加排产池
    addApsPool: function () {
        page.disableBtn();
        var url = page.rootPath + "/forms/ApsPages/ApsLMContainerSelect.html?v=" + new Date().getTime();
        url += "&parentDiv=dg";

        $('#dg').dialog({
            title: '选择批次到排产池',
            fit: true,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            returnData: null,
            popupData: '', //弹出页面的传参
            onClose: function () {
                var returnData = $("#dg").dialog('options').returnData; //返回数据
                if (returnData != null) {
                    //console.log('更新父级数据');
                    page.searchData();
                    displayMessage("添加成功", true);
                }
                page.enableBtn();
            }
        });
    },
    //移除排产池
    removeApsPool: function () {
        var selectData = $('#gdApsContainer').datagrid('getChecked');
        if (selectData.length == 0) {
            displayMessage("请选择数据", false);
            return;
        }
        var param = {
            action: "removeApsPool",
            containers: JSON.stringify(selectData)
        };
        page.disableBtn();
        page.post(page.apsUrl, param, true, function (res) {
            if (res.Result) {
                page.searchData();
            }
            displayMessage(res.Message, res.Result);
            page.enableBtn();
        });
    },
    //查看甘特图
    viewGantt: function (containerID) {
        var url = "RbApsLimitedCapacityViewPage.html?v=" + new Date().getTime() + "&parentDiv=dg";
        $('#dg').dialog({
            title: '批次工序计划甘特图-有限产能',
            fit: true,
            top: 10,
            closed: false,
            cache: false,
            modal: true,
            content: '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="auto"></iframe>',
            popupData: { containerID: containerID }, //弹出页面的传参
            returnData: null,
            onClose: function () {
                page.searchData();
            }
        });
    },
    //导出排产异常数据
    exportApsLog: function () {
        var poolID = $("#txtPoolID").combobox("getValue"); //获取排产池
        if (poolID === "" || poolID === null) {
            displayMessage("请选择排产池", false);
            return;
        }
        FileDownLoad(page.url, { action: "ExportContainerApsLogInfo", poolID: poolID });
    },
    //查看工艺的工步期量信息
    linkStepInfoParam: function (pID, pName, wID, wName) {
        page.post(page.url, { action: "GetLinkWorkflowInfo", workflowID: wID }, true, function (res) {
            if (res.Result) {
                if (res.ReturnData !== "") {
                    wID = res.ReturnData.workflowid;
                    pId = res.ReturnData.productid;
                    pName = res.ReturnData.productname;
                    wName = res.ReturnData.workflowname;
                }
                var url = "forms/Custom/ReBiao/RBStepParameterMaintPage.html?" +
                     "pname=" + pName + "&pid=" + pID + "&wname=" + wName + "&wid=" + wID;
                // 创建一个新的a标签
                var $a = $('<a>', {
                    target: '_blank',
                    on: {
                        click: top.mainWorkPage.addTab('APS-工步生产周期维护', url, true)
                    }
                });
                $a.click();
            }
        });
    },
    //打开维护指定时间弹窗
    openHandTimeForm: function () {
        var selectData = $('#gdApsContainer').datagrid('getChecked');
        if (selectData.length === 0) {
            displayMessage("请选择数据", false);
            return;
        }
        var datas = selectData.map(function (item) {
            return {
                CONTAINERID: item.CONTAINERID,
                EXPECTMATERIALDATE: item.EXPECTMATERIALDATE
            }
        });
        handTimePage.init(datas);
    },
    //禁用页面按钮
    disableBtn: function () {
        $("#mainSec").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('disable');
        });
    },
    //启用页面按钮
    enableBtn: function () {
        $("#mainSec").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('enable');
        });
    },
    //清除页面（查询区域，列表区域，是否清空消息）
    clearPage: function (query, list, msg) {
        if (query) {
            $("#txtMainFactoryID").combobox("clear"); //主制分厂
            $("#txtMfgorderName").textbox("clear"); //订单号
            $("#txtApsOverdue").textbox("clear"); //排产超期
            $("#txtContainerName").textbox("clear"); //流水卡
            $("#txtFaContainerName").textbox("clear"); //主制流水卡
        }
        if (list) {
            clearEasyuiDataGrid("gdApsContainer"); //清空列表
        }
        if (msg) {
            clearMessage();
        }
    },
    //post数据（路径，参数，是否异步，成功返回方法）
    post: function (url, param, async, callback) {
        $.ajax({
            type: "Post",
            url: url,
            data: param,
            cashe: false,
            async: async,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
                page.enableBtn();
            }
        });
    }
};
/*---------手动指定开始日期弹窗页面对象-------------*/
var handTimePage = {
    selectedDatas: null, //所选批次信息
    init: function (rowDatas) {
        handTimePage.clearPage();
        page.disableBtn();
        handTimePage.selectedDatas = rowDatas;
        handTimePage.initData();
        $("#dgManual").dialog({
            onClose: function () { //弹窗关闭事件
                page.enableBtn();
            }
        });
    },
    //初始化页面数据
    initData: function () {
        if (handTimePage.selectedDatas.length === 1) {
            if (handTimePage.selectedDatas[0].EXPECTMATERIALDATE !== null) {
                $("#manualStartDate").datetimebox("setValue", handTimePage.selectedDatas[0].EXPECTMATERIALDATE);
            }
        }
    },
    //保存手动指定日期
    saveManualDate: function () {
        if (handTimePage.selectedDatas === null) {
            displayMessage("未选择批次", false);
            return;
        }
        var formData = {
            action: "SaveManualStartDate",
            containerDatas: JSON.stringify(handTimePage.selectedDatas),
            manualStartDate: $("#manualStartDate").datetimebox("getValue")
        };
        page.post(page.url, formData, true, function (res) {
            if (res.Result) {
                $("#dgManual").dialog("close");
                page.searchData();
            }
            handTimePage.enableBtn();
            displayMessage(res.Message, res.Result);
        });
    },
    //清除页面数据
    clearPage: function () {
        handTimePage.selectedDatas = null;
        $("#manualStartDate").datetimebox("clear");
    },
    //禁用按钮
    disableBtn: function () {
        $("#dgManual").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('disable');
        });
    },
    //启用按钮
    enableBtn: function () {
        $("#dgManual").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('enable');
        });
    }
};
$(function () {
    page.init();
});